package org.example.controller;

import com.github.wxpay.sdk.WXPayUtil;
import org.example.service.IOrderService;
import org.example.websocket.WebSocketService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wxPay")
public class PayController {

    @Resource
    private IOrderService iOrderService;

    @PostMapping("/success")
    public String success(HttpServletRequest request) throws  Exception{
        //获取请求输入流
        ServletInputStream is = request.getInputStream();
        //设置每次读取的大小为1024字节
        byte[] bs = new byte[1024];
        int len = -1;
        //将流中信息封装到StringBuffer字符串中
        StringBuffer buffer = new StringBuffer();
        //循环读取
        while ((len = is.read(bs)) != -1){
            buffer.append(new String(bs,0,len));
        }
        String str = buffer.toString();
        //通过此方法将规范的字符串转化为map集合
        Map<String, String> map = WXPayUtil.xmlToMap(str);

        //确认微信支付成功
        if (map != null && map.get("result_code").equalsIgnoreCase("success")){
            //支付成功后给前端反馈
            WebSocketService.sendMsg(map.get("out_trade_no"),"1");

            String out = map.get("out_trade_no").substring(0, 27);
            iOrderService.updateStatus(out);

            //封装返回给微信服务器的信息，理由是此订单已经支付完成了，不需要再对服务器请求了
            HashMap<String, String> resp = new HashMap<>();
            //以下是微信服务器所必要的信息
            resp.put("return_code","success");
            resp.put("return_msg","ok");
            resp.put("appid",map.get("appid"));
            resp.put("result_code","success");
            //微信需要接受的是String类型，所以需要以下方法转化为字符串
            return WXPayUtil.mapToXml(map);
        }
        return null;
    }

}
